package com.ouc.ouc.interceptor;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import io.terminus.common.utils.Splitters;

import io.terminus.pampas.engine.SettingHelper;
import io.terminus.pampas.engine.ThreadVars;
import io.terminus.pampas.engine.model.App;
//import com.ouc.pampas.ThreadVars;
//import com.ouc.pampas.App;
//import com.ouc.pampas.SettingHelper;

public class AppInterceptor extends HandlerInterceptorAdapter
{
  @Autowired
  private SettingHelper settingHelper;
  
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception
  {
    List<String> host = Splitters.COLON.splitToList(request.getHeader("Host"));
    String domain = ((String)host.get(0)).toLowerCase();
    App app = this.settingHelper.findAppByDomain(domain);
    if (app == null) {
      throw new Exception("app not found");
    }
    if (host.size() > 1) {
      ThreadVars.setPort(Integer.valueOf((String)host.get(1)));
    }
    ThreadVars.setDomain(domain);
    ThreadVars.setLocale(request.getLocale().toString());
    ThreadVars.setApp(app);
    return true;
  }
  
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    throws Exception
  {
    ThreadVars.clearPort();
    ThreadVars.clearDomain();
    ThreadVars.clearLocale();
    ThreadVars.clearApp();
  }
}
